// 使用storage
const useStorage = ($storage: Storage) => {
    // 根据key获取storage中的数据
    const get = (key: string) => {
        const value = $storage.getItem(key)
        if (!value) return value
        try {
            return JSON.parse(value)
        } catch {
            return value
        }
    }

    // 设置storage数据
    const set = (key: string, value: any) => {
        const data = typeof value === 'string' ? value : JSON.stringify(value)
        return $storage.setItem(key, data)
    }

    // 移植值
    const remove = (key: string) => {
        return $storage.removeItem(key)
    }

    // 清空storage
    const clear = () => {
        for (const key in $storage) {
            if (key) $storage.removeItem(key)
        }
    }

    return {
        get,
        set,
        remove,
        clear,
    }
}

const LocalStorage = useStorage(window.localStorage || localStorage)
const SessionStorage = useStorage(window.sessionStorage || sessionStorage)

export { LocalStorage, SessionStorage }
